/*
 * sysLogger.c
 *
 *  Created on: Dec 24, 2011
 *      Author: shaohong
 */

#include "sysLogger.h"

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <assert.h>
#include "errorLogging.h"
#include "fileLockHelper.h"

const char * FIFO_NAME = "/var/log/mySyslogd.FIFO";

const char * LOG_FILE_NAME = "/var/log/shaohongSyslogd.log";

static char *LOG_FILE_MODE = "a";

static FILE * logfp = NULL;

/* the output buffer that we'll use for logging the message */
static char printBuffer[1024];


/*open the logFile for logging.*/
void openLogFile() {

	/* Don't open the logfile twice. */
	if (logfp != NULL)
	{
		log_msg("logfile is already opened");
		return;
	}

	/* If we fail to open the log file, the whole program will terminate*/
	logfp = fopen(LOG_FILE_NAME, LOG_FILE_MODE);
	if (NULL == logfp) {
		sprintf(printBuffer,
				"Failed to open logfile \"%s\"\n Program will terminate!!!",
				LOG_FILE_NAME);
		log_quit(printBuffer);
		exit(-1);
	}

	log_msg("logfile %s is opened for appending", LOG_FILE_NAME);

	//put a file lock on the logfile
	if (EXIT_FAILURE == setFileLock(fileno(logfp), F_WRLCK, false)) {
		log_quit("failed to acquire write lock on %s. ", LOG_FILE_NAME);
	}
}

void logMsg(const char * msg) {

	assert(NULL != msg);

	if (NULL == logfp) {
		openLogFile();
	}

	fprintf(logfp, "%s", msg);
	fflush(logfp);
}

void closeLogFile() {
	if (NULL != logfp) {
		fclose(logfp);
	}
}

